﻿using fastdbServer.BasicModel;
using Newtonsoft.Json;

namespace fastdbServer.Middleware
{
    public class GlobalErrorHandlerMiddleWare
    {
        private readonly RequestDelegate _next;

        public GlobalErrorHandlerMiddleWare(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            var errorMsg = string.Empty;

            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
            }

            if (!string.IsNullOrEmpty(errorMsg))
                await OutputJsonData(context, Result.CreateFailed(errorMsg)).ConfigureAwait(false);
        }

        /// <summary>
        ///     输出json格式的数据
        /// </summary>
        /// <param name="context"></param>
        /// <param name="resp"></param>
        /// <returns></returns>
        public static async Task OutputJsonData(HttpContext context, Result resp)
        {
            if (context.Response.HasStarted) return;

            //返回友好的提示
            context.Response.ContentType = "application/json;charset=utf-8";
            await context.Response.WriteAsync(JsonConvert.SerializeObject(resp)).ConfigureAwait(false);
        }
    }
}